<!-- 登录组件
 -->
<template>
  <div id="myLogin">
    <el-dialog title="登录" width="400px" center :visible.sync="isLogin">
      <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="phone">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入手机号" v-model="LoginUser.phone"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="LoginUser.pass"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Login" style="width:100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import cookie from 'js-cookie'
export default {
  name: "MyLogin",
  data() {
    // 手机号的校验方法
     let validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      const userNameRule = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
      if (userNameRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("请输入正确的手机号"));
      }
    };
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    return {
      LoginUser: {
        phone: "",
        pass: ""
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  computed: {
    // 获取vuex中的showLogin，控制登录组件是否显示
    isLogin: {
      get() {
        return this.$store.getters.getShowLogin;
      },
      set(val) {
        this.$refs["ruleForm"].resetFields();
        this.setShowLogin(val);
      }
    }
  },
  methods: {
    ...mapActions(["setUser" ,"setUserInfo", "setShowLogin","setShopcarNumber"]),
    Login() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(async valid => {
        //如果通过校验开始登录
        if (valid) {
          const {data:res} = await this.$http.post('/xuanmall/wzxusermessage/login',{
             password: this.LoginUser.pass,
            mobile:this.LoginUser.phone,
          })
         if(res.code === 0){
          cookie.set("token", res.token, { domain: "localhost" });
        // 调用接口根据token获取用户信息，为首页显示
          const {data:res1} = await  this.$http.post('/xuanmall/wzxusermessage/info') 
          // console.log("qqq",res1)
          if(res1.msg ==='success'){
            this.setUser(res1.userInfo);
            // 获取返回的用户信息放到cookie
            let user = JSON.stringify(res1.userInfo);
            cookie.set("user",user,{domain:'localhost'})
             const { data: res } = await this.$http.get("/xuanmall/cart/list");
              if (res.code === 0) {
                console.log("购物车", res);
                this.$store.dispatch("setShopcarNumber", res.cartVOS.length);
                cookie.set("shopcarNumber", res.cartVOS.length, { domain: "localhost" });
              }
            // localStorage.setItem("user",user)
            // this.$store.dispatch("setShowLogin",true);
            // this.setShowLogin(true)
            // 隐藏登录组件
            this.isLogin = false;
          // 弹出通知框提示登录成功信息
          this.$message.success("登录成功")
          }
         }
         else {
            // 清空输入框的校验状态
            this.$refs["ruleForm"].resetFields();
            // 弹出通知框提示登录失败信息
            this.notifyError("登录失败");
          }
        }
      });
    }
  }
};
</script>
<style>
</style>